package com.home.service;

import com.home.entity.Department;
import com.home.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    public List<Department> getAllDepartments() {
        return departmentMapper.getAllDepartmentsByParentId(-1);
    }

    @Transactional
    public String addDept(Department department) {
        Integer parentId = department.getParentid();
        Department parentDept = departmentMapper.selectByPrimaryKey(parentId);
        System.out.println("parentDept==" + parentDept.toString());
        if (parentDept != null) {
            parentDept.setIsparent(true);
            departmentMapper.updateByPrimaryKeySelective(parentDept);
        }
        departmentMapper.insertSelectiveReturnId(department);
        int returnID = department.getId();
        department.setDeppath(parentDept.getDeppath() + "." + returnID);
        int i = departmentMapper.updateByPrimaryKeySelective(department);
        if (i == 1) {
            return "新增部门成功";
        } else {
            return "新增部门失败";
        }
    }

    @Transactional
    public String deleteById(Integer id) {
        Department department = departmentMapper.selectByPrimaryKey(id);
        if (department.getIsparent()) {
            return "该部门有子部门，无法删除！";
        }
        Integer parentId = department.getParentid();
        Department departmentParent4DB = departmentMapper.selectByPrimaryKey(parentId);
        String departmentParent4DBPath = departmentParent4DB.getDeppath() + ".";
        List<Department> lists = departmentMapper.getDepPathLike(departmentParent4DBPath);
        if (lists.size() == 1) {
            departmentMapper.deleteByPrimaryKey(id);
            departmentParent4DB.setIsparent(false);
            departmentMapper.updateByPrimaryKeySelective(departmentParent4DB);
            return "删除成功";
        } else {
            departmentMapper.deleteByPrimaryKey(id);
            return "删除成功";
        }
    }

    public List<Department> getAllDepartmentsWithOutChildren() {
        return departmentMapper.getAllDepartmentsWithOutChildren();
    }
//    public static void main(String[] args) {
//        String str = "10.50.1162.abc";
//        int i = str.lastIndexOf(".");
//        String substring = str.substring(0, i);
//        System.out.println(substring);
//    }
}
